package app

import (
	"context"
	"fmt"

	// _ "net/http/pprof"
	"nd-app/internal/icontext"
	"nd-app/pkg/factory"
	"nd-app/pkg/logger"
)

type App struct {
	ctx    context.Context
	cancel context.CancelFunc
}

var app *App

func Init(configFile string) error {
	app = &App{}

	if err := factory.Init(configFile); err != nil {
		logger.AppLog.Errorln("init config factory fail:", err)
		return err
	}

	config := factory.AppConfig
	lvl := config.Logger.LogLevel
	logger.AppLog.Infoln("Setting log level to:", lvl)
	logger.SetLogLevel(lvl)

	if err := icontext.Init(); err != nil {
		logger.AppLog.Errorln("init upc fail:", err)
		return err
	}

	return nil
}

func Final() error {
	if err := icontext.Final(); err != nil {
		logger.AppLog.Errorln("final upc fail:", err)
		return err
	}
	if err := factory.Final(); err != nil {
		logger.AppLog.Errorln("final config factory fail:", err)
		return err
	}
	app = nil
	return nil
}

func Start() error {
	if app == nil {
		return fmt.Errorf("app is nil")
	}

	ctx, cancel := context.WithCancel(context.Background())
	app.ctx = ctx
	app.cancel = cancel

	go icontext.Start()

	// go http.ListenAndServe("192.168.99.51:9905", nil)

	logger.AppLog.Infoln("app start success")

	return nil
}

func Wait() error {
	if app == nil {
		return fmt.Errorf("app is nil")
	}
	if app.ctx == nil {
		return fmt.Errorf("app.ctx is nil")
	}

	<-app.ctx.Done()

	return nil
}

func Stop() error {
	if app == nil {
		return fmt.Errorf("app is nil")
	}
	if app.cancel == nil {
		return fmt.Errorf("app.cancel is nil")
	}

	app.cancel()

	return nil
}
